﻿using System.Text;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace BoxSauce.AgencyToolkit.Xml
{
    /// <summary>
    /// Xml Serializing Tools
    /// </summary>
    public class Serialiser
    {
        /// <summary>
        /// Deserialize xml string to object of type T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string xmlString)
        {
            var serializer = new XmlSerializer(typeof(T));
            var document = XDocument.Parse(xmlString);
            return (T)serializer.Deserialize(document.CreateReader());
        }

        /// <summary>
        /// Serializes object to xml string
        /// </summary>
        /// <param name="xmlObject"></param>
        /// <returns></returns>
        public static string Serialize(object xmlObject)
        {
            var serializer = new XmlSerializer(xmlObject.GetType());
            var sb = new StringBuilder();
            var writer = new System.IO.StringWriter(sb);
            serializer.Serialize(writer, xmlObject);

            return sb.ToString();
        }   
    }
}
